package com.jin.crud.common.config.security;

import com.alibaba.fastjson.JSON;
import com.jin.crud.common.code.HttpCodeEnum;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * @Author yuxuejin
 * @Date 2021/11/25 23:07
 * @Description: 认证失败处理类 返回未授权
 */
@Slf4j
//@Component
public class JwtAuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("认证失败：{}", e.getMessage());
        int code = HttpCodeEnum.UNAUTHORIZED_ERROR.getCode();
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        //ServletUtils.renderString(response, JSON.toJSONString(new ResultException(code, msg)));
        String body = JSON.toJSONString(new ResultException(HttpCodeEnum.UNAUTHORIZED_ERROR.getCode(), e.getMessage()));
        printWriter.write(body);
        printWriter.flush();
    }
}
